package com.lin.learning.questionmanagement.service.serviceimpl;

import com.lin.learning.questionmanagement.service.LoginService;
import com.lin.learning.questionmanagement.utils.JwtUtil;
import com.lin.learning.questionmanagement.utils.RedisCache;
import com.lin.learning.questionmanagement.vo.UserVo;

import com.our.learning.infrastructure.po.User;

import com.our.learning.infrastructure.pojo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public ResponseResult userLogin(User user) {
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(user.getAccount(),user.getPassword());
        Authentication authentication=authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authentication)){
            // TODO: 2023-06-18 抛出异常，用户名或密码错误
        }
        User loginuser=(User) authentication.getPrincipal();
        String id= loginuser.getId().toString();
        String jwt= JwtUtil.createJWT(id);
        redisCache.setCacheObject("login:"+id,user);
        UserVo vo=new UserVo(id,loginuser.getAccount(),jwt,loginuser.getType());
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User loginUser=(User) authentication.getPrincipal();
        //获取id
        Integer id=loginUser.getId();
        redisCache.deleteObject("login:"+id);
        return ResponseResult.okResult();
    }
}
